/*
* Copyright (c) 2016 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
*/
package com.hyyt.shopjsp.util.interceptor;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * 防止sql注入初步拦截器处理
 *
 * @author ankang
 * @Date 2016/7/22 0022 下午 5:06
 */
public class SqlFilterInterceptor extends HandlerInterceptorAdapter {
    Log logger = LogFactory.getLog(this.getClass());

    /**
     * 拦截sql注入特征的请求<p/>
     * 1.获得所有的请求参数<p/>
     * 2.单个获得参数然后进行value过滤处理<p/>
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Enumeration<String> param_names = request.getParameterNames(); //获得所有的请求参数
        while (param_names.hasMoreElements()) {
            String param_name = param_names.nextElement();//获得参数名称
            String[] values = request.getParameterValues(param_name); //根据参数名称获得value值
            logger.info("传入参数为：" + param_name + "=>>" + JSON.toJSONString(values));
            for (int i = 0; i < values.length; i++) {
                if (StringUtils.isNotBlank(values[i])) {//判断内容是否为空，不为空进行处理
                    String val_sql = values[i].toLowerCase();
                    if (val_sql.contains("select ") || val_sql.contains("create ") || val_sql.contains("drop ") || val_sql.contains("delete ") || val_sql.contains("insert ") || val_sql.contains("update ")) {/*判断注入的sql关键字*/
                        response.setContentType("text/html;charset=utf-8");
                        response.getWriter().print("非法操作！<br/><a href='javascript:' onclick='history.go(-1)'>返回</a>");
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
